package com.lsec.springbootinit.security.handler;

import com.lsec.springbootinit.exception.enums.TypicalCode;
import com.lsec.springbootinit.model.common.CommonResult;
import com.lsec.springbootinit.security.utils.SecurityFrameworkUtils;
import com.lsec.springbootinit.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.ExceptionTranslationFilter;


/**
 * 访问一个需要认证的 URL 资源，已经认证（登录）但是没有权限的情况下, 定义了全局异常处理器 所以不会走此类  accessDeniedExceptionHandler
 *
 * 补充：Spring Security 通过 {@link ExceptionTranslationFilter#handleAccessDeniedException(HttpServletRequest, HttpServletResponse, FilterChain, AccessDeniedException)} 方法，调用当前类
 *
 * @author 芋道源码
 */
@Slf4j
@SuppressWarnings("JavadocReference")
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) {
        // 打印 warn 的原因是，不定期合并 warn，看看有没恶意破坏
        log.warn("[commence][访问 URL({}) 时，用户({}) 权限不够]", request.getRequestURI(),
                SecurityFrameworkUtils.getLoginUserId(), e);
        // 返回 403
        ServletUtils.writeJson(response, CommonResult.error(TypicalCode.FORBIDDEN_403));
    }

}
